package cn.paul.controller;

import cn.paul.pojo.Item;
import cn.paul.service.ItemService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("item")
public class ItemController {
    @Autowired
    private ItemService service;

//    @RequestMapping("itemQuery")
//    public String itemList(Item item, String pageNum, Model model) {
//
//        PageInfo<Item> pageInfo = service.selectSelective(item, pageNum);
//        model.addAttribute("page", pageInfo);
//        return "itemList";
//
//    }

    @RequestMapping("itemQuery2")
    public String itemList2() {
        return "itemList2";

    }

    //返回json数据给前台
    @ResponseBody
    @RequestMapping("getItems")
    public Map itemPageInfo(Item item, String page, String rows) {
        PageInfo<Item> pageInfo = service.selectSelective(item, page, rows);
        Map<String,Object> map = new HashMap<>();
        map.put("rows", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return map;
    }

    //保存商品
    @PostMapping("newItem")
    public void saveItem(Item item, @RequestPart Part pic) {
        try {
            String fileName = new String(pic.getSubmittedFileName().getBytes(), "UTF-8");
            if (!fileName.equals("")) {
                String saveFileName = System.currentTimeMillis() + "aaaabba" + fileName;
                item.setPic(saveFileName);
                pic.write("D:/上传目录/" + saveFileName);
            }
            service.addItem(item);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //修改商品信息
    @PostMapping("/updateItem/{id}")
    public void updateItem(Item item, @PathVariable() String id,@RequestPart Part pic) throws IOException {
        item.setId(Integer.parseInt(id));
        String fileName = new String(pic.getSubmittedFileName().getBytes(), "UTF-8");
        if (!fileName.equals("")) {
            String saveFileName = System.currentTimeMillis() + "aaaabba" + fileName;
            item.setPic(saveFileName);
            pic.write("D:/上传目录/" + saveFileName);
        }
        service.update(item);
    }

    //删除商品
    @RequestMapping("deleteItems")
    public void deleteItem(String ids) {
        if (ids != null) {
          String[] idArray =  ids.split(",");

          for(String id:idArray){
              service.delete(Integer.parseInt(id));
          }
        }
    }
}
